#include "board.h"
#define DBG_TAG "MAIN"
#define CONFIG_LOG_LEVEL 3
#define CONFIG_LOG_NCOLOR 1
#include "log.h"
#include "bflb_mtimer.h"
#include "bl616_glb.h"
#include "bl_fw_api.h"
#include "wifi_mgmr.h"
#include "lwip/tcpip.h"


#include "FreeRTOS.h"
#include "task.h"

#include "shell.h"
#include "task_kill.h"


#define WIFI_STACK_SIZE  (1536)
#define TASK_PRIORITY_FW (16)

TaskHandle_t wifi_fw_task;

extern void shell_init_with_task(struct bflb_device_s* shell);

int wifi_start_firmware_task(void)
{
    LOG_I("Starting wifi ...\r\n");

    /* enable wifi clock */

    GLB_PER_Clock_UnGate(GLB_AHB_CLOCK_IP_WIFI_PHY | GLB_AHB_CLOCK_IP_WIFI_MAC_PHY | GLB_AHB_CLOCK_IP_WIFI_PLATFORM);
    GLB_AHB_MCU_Software_Reset(GLB_AHB_MCU_SW_WIFI);

    /* set ble controller EM Size */

    GLB_Set_EM_Sel(GLB_WRAM160KB_EM0KB);

    if (0 != rfparam_init(0, NULL, 0)) {
        LOG_I("PHY RF init failed!\r\n");
        return 0;
    }

    LOG_I("PHY RF init success!\r\n");

    /* Enable wifi irq */

    extern void interrupt0_handler(void);
    bflb_irq_attach(WIFI_IRQn, (irq_callback)interrupt0_handler, NULL);
    bflb_irq_enable(WIFI_IRQn);

    xTaskCreate(wifi_main, (char*)"fw", WIFI_STACK_SIZE, NULL, TASK_PRIORITY_FW, &wifi_fw_task);

    return 0;
}

void wifi_event_handler(uint32_t code)
{
    printf("[WIFI EVENT]: %d\n", code);
}

void test_task(char* args)
{
    while (1)
    {
        printf("test task\n");
        vTaskDelay(5000);
    }
}

int main(void)
{
    board_init();
    LOG_I("-----------board init-----------");

    
    struct bflb_device_s* uart0;
    //获取uart0串口
    uart0 = bflb_device_get_by_name("uart0");
    //初始化shell
    shell_init_with_task(uart0);

    tcpip_init(NULL, NULL);

    wifi_start_firmware_task();

    xTaskCreate(test_task, "test", 128, NULL, 10, NULL);

    vTaskStartScheduler();

    while (1)
    {
        bflb_mtimer_delay_ms(1000);
    }
}
